<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="关键字" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="请输入关键字"
          clearable
          class="!w-[150px]"
        />
      </el-form-item>
      <el-form-item label="用户telegramId" prop="telegramId">
        <el-input
          v-model="form.telegramId"
          placeholder="请输入用户telegramId"
          clearable
          class="!w-[150px]"
        />
      </el-form-item>
      <el-form-item label="指定用户" prop="userId">
        <el-select
          ref="userSelectRef"
          v-model="form.userId"
          placeholder="请选择"
          filterable
          remote
          :remote-method="onKeywordInput"
          class="!w-[180px]"
          clearable
          @visible-change="onUserDropdownVisibleChange"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
          <template v-if="userLoading" #footer>
            <div class="text-center text-xs text-gray-500">
              <span>加载中...</span>
            </div>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="通知级别" prop="notificationLevel">
        <el-select
          v-model="form.notificationLevel"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in levelList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否接收文件" prop="receiveFiles">
        <el-select
          v-model="form.receiveFiles"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in receiveList"
            :key="item.label"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="绑定状态" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序字段" prop="orderBy">
        <el-input
          v-model="form.orderBy"
          placeholder="请输入排序字段"
          clearable
          class="!w-[150px]"
        />
      </el-form-item>
      <el-form-item label="排序方向" prop="orderDirection">
        <el-select
          v-model="form.orderDirection"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option
            v-for="item in orderList"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-table
      show-overflow-tooltip
      stripe
      border
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column prop="username" label="用户名称" width="120" />
      <el-table-column prop="telegramId" label="telegramId" width="120" />
      <el-table-column prop="firstName" label="姓" width="120" />
      <el-table-column prop="lastName" label="名" width="120" />
      <el-table-column prop="statusDescription" label="绑定状态" width="120" />
      <el-table-column
        prop="notificationLevelDesc"
        label="通知级别"
        width="160"
      />
      <el-table-column
        prop="receiveFiles"
        :formatter="receiveFormatter"
        label="是否接受文件"
        width="160"
      />
      <el-table-column
        prop="createTime"
        :formatter="val => handleAutoUTC8(val.createTime)"
        label="创建时间"
      />

      <el-table-column
        prop="updateTime"
        :formatter="val => handleAutoUTC8(val.updateTime)"
        label="更新时间"
      />
      <el-table-column label="操作" width="340">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            size="small"
            @click="openUnBindDialog(row)"
          >
            强制解绑用户
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="openFilesDialog(row)"
          >
            设置接收文件
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="openLevelDialog(row)"
          >
            设置通知级别
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <FilesReceiveDialog ref="filesReceiveRef" @refresh="onSearch" />
    <LevelDialog ref="levelRef" @refresh="onSearch" />
    <UnBindDialog ref="unBindRef" @refresh="onSearch" />
  </div>
</template>

<script lang="ts" setup>
import { handleAutoUTC8 } from "@/utils/tools";
import { ref, onMounted, reactive, nextTick } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import {
  getTelegramUserList,
  getTelegramUserDetail
} from "@/api/adminTelegramApi";
import FilesReceiveDialog from "./components/FilesReceiveDialog.vue";
import LevelDialog from "./components/LevelDialog.vue";
import UnBindDialog from "./components/UnBindDialog.vue";
import {
  userSelectFetcher,
  type UserItem
} from "@/composables/userSelectFetcher";
import { type ElSelect } from "element-plus";
import { useRemotePagedSelect } from "@/composables/useRemotePagedSelect";

// 用户下拉：远程搜索 + 触底加载
const {
  list,
  loading: userLoading,
  onKeywordInput,
  onDropdownScroll
} = useRemotePagedSelect<UserItem>({
  pageSize: 20,
  autoLoad: true,
  debounceMs: 300,
  fetcher: userSelectFetcher
});

const userSelectRef = ref<InstanceType<typeof ElSelect> | null>(null);
let userDropdownWrapEl: HTMLElement | null = null;

function onUserDropdownVisibleChange(visible: boolean) {
  if (visible) {
    nextTick(() => {
      const popperEl = userSelectRef.value?.popperRef as
        | HTMLElement
        | undefined;
      // 在该选择器自己的 popper 里找 wrap
      userDropdownWrapEl =
        popperEl?.querySelector(".el-select-dropdown__wrap") ?? null;
      userDropdownWrapEl?.addEventListener("scroll", onDropdownScroll, {
        passive: true
      });
    });
  } else {
    userDropdownWrapEl?.removeEventListener("scroll", onDropdownScroll);
    userDropdownWrapEl = null;
  }
}

const formRef = ref();
const loading = ref(false);
const filesReceiveRef = ref();
const openFilesDialog = (row: { userId: number; receiveFiles: boolean }) => {
  filesReceiveRef.value?.open(row.userId, row.receiveFiles);
};
const levelRef = ref();
const openLevelDialog = (row: {
  userId: number;
  notificationLevel: string;
}) => {
  levelRef.value?.open(row.userId, row.notificationLevel);
};
const unBindRef = ref();
const openUnBindDialog = (row: { userId: number }) => {
  unBindRef.value?.open(row.userId);
};
const details = async (id: number) => {
  try {
    const res = await getTelegramUserDetail(id);
    console.log(res, "res");
  } catch (error) {
    console.log(error);
  }
};
const form = reactive({
  keyword: "",
  status: "",
  notificationLevel: "",
  receiveFiles: "",
  userId: "",
  telegramId: "",
  orderBy: "updateTime",
  orderDirection: "desc"
});
const levelList = [
  {
    label: "所有通知",
    value: "ALL"
  },
  {
    label: "仅业务通知",
    value: "BUSINESS_ONLY"
  },
  {
    label: "无消息",
    value: "NONE"
  }
];
const receiveList = [
  {
    label: "是",
    value: true
  },
  {
    label: "否",
    value: false
  }
];
const orderList = [
  {
    label: "升序",
    value: "asc"
  },
  {
    label: "降序",
    value: "desc"
  }
];
const statusList = [
  {
    label: "已绑定",
    value: "ACTIVE"
  },
  {
    label: "未绑定",
    value: "PENDING"
  }
];
const receiveFormatter = (row: any) => {
  return (
    receiveList.find(item => item.value === row.receiveFiles)?.label || "--"
  );
};
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
});
const tableData = ref([]);

async function onSearch() {
  const params = {
    pageNum: pagination.currentPage,
    pageSize: pagination.pageSize,
    ...form
  };
  const { data } = await getTelegramUserList(params);
  const { list, total, pageSize, pageNum } = data;
  tableData.value = list;
  pagination.total = total;
  pagination.pageSize = pageSize;
  pagination.currentPage = pageNum;
}
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  pagination.currentPage = 1;
  onSearch();
};
onMounted(() => {
  onSearch();
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  gap: 20px;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style>
